<template>
  <div class="model-overview">
    <div class="page-header">
      <h1>模型概览</h1>
    </div>
    
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card shadow="hover" class="mb-4" v-loading="loadingActiveModel">
          <template #header>
            <div class="card-header">
              <span>当前活动模型</span>
            </div>
          </template>
          <el-empty 
            v-if="!activeModel" 
            description="暂无活动模型" 
          >
            <el-button type="primary" @click="goToTraining">创建模型</el-button>
          </el-empty>
          <el-descriptions border v-else>
            <el-descriptions-item label="模型名称">{{ activeModel.name }}</el-descriptions-item>
            <el-descriptions-item label="模型类型">{{ activeModel.model_type_display }}</el-descriptions-item>
            <el-descriptions-item label="准确率">{{ formatPercent(activeModel.accuracy) }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ activeModel.created_at_formatted }}</el-descriptions-item>
            <el-descriptions-item label="最近更新">{{ activeModel.updated_at_formatted }}</el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag type="success">活动中</el-tag>
            </el-descriptions-item>
          </el-descriptions>
          <div class="model-actions" v-if="activeModel">
            <el-button type="primary" @click="viewModelDetails(activeModel.id)">查看详情</el-button>
            <el-button type="success" @click="goPrediction">进行预测</el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card shadow="hover" v-loading="loadingModels">
          <template #header>
            <div class="card-header">
              <span>所有模型</span>
              <div>
                <el-button type="primary" size="small" @click="goToTraining">创建新模型</el-button>
                <el-button type="info" size="small" @click="refreshModels">刷新</el-button>
              </div>
            </div>
          </template>
          
          <!-- 过滤和搜索 -->
          <el-row :gutter="20" class="filter-row">
            <el-col :span="6">
              <el-select
                v-model="filters.model_type"
                placeholder="模型类型"
                clearable
                style="width: 100%"
                @change="handleFilterChange"
              >
                <el-option
                  v-for="type in modelTypes"
                  :key="type.value"
                  :label="type.label"
                  :value="type.value"
                />
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-select
                v-model="filters.status"
                placeholder="模型状态"
                clearable
                style="width: 100%"
                @change="handleFilterChange"
              >
                <el-option label="训练中" value="training" />
                <el-option label="已完成" value="completed" />
                <el-option label="失败" value="failed" />
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-input
                v-model="filters.search"
                placeholder="搜索模型名称"
                clearable
                @input="handleFilterChange"
              />
            </el-col>
          </el-row>
          
          <!-- 模型表格 -->
          <el-table :data="modelsList" style="width: 100%">
            <el-table-column prop="name" label="模型名称" width="180" />
            <el-table-column prop="model_type_display" label="模型类型" width="180" />
            <el-table-column prop="accuracy" label="准确率">
              <template #default="scope">
                {{ formatPercent(scope.row.accuracy) }}
              </template>
            </el-table-column>
            <el-table-column prop="created_at_formatted" label="创建时间" />
            <el-table-column prop="updated_at_formatted" label="更新时间" />
            <el-table-column prop="status" label="状态">
              <template #default="scope">
                <el-tag :type="getStatusTagType(scope.row.status)">
                  {{ scope.row.status_display }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="220">
              <template #default="scope">
                <el-button 
                  v-if="scope.row.status === 'completed'"
                  :type="scope.row.is_active ? 'info' : 'success'" 
                  size="small"
                  :disabled="scope.row.is_active"
                  @click="activateModel(scope.row.id)"
                >
                  {{ scope.row.is_active ? '当前活动' : '激活' }}
                </el-button>
                <el-button 
                  type="primary" 
                  size="small"
                  @click="viewModelDetails(scope.row.id)"
                >
                  详情
                </el-button>
                <el-button 
                  type="danger" 
                  size="small"
                  :disabled="scope.row.is_active"
                  @click="confirmDeleteModel(scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="pagination.page"
              v-model:page-size="pagination.pageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next"
              :total="pagination.total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="ModelOverview">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getModels, 
  getActiveModel, 
  activateModel as activateModelApi,
  deleteModel as deleteModelApi,
  getModelTypes as getModelTypesApi
} from '@/api/modules/models'

// 路由
const router = useRouter()

// 数据加载状态
const loadingActiveModel = ref(false)
const loadingModels = ref(false)
const loadingModelTypes = ref(false)

// 模型数据
const activeModel = ref(null)
const modelsList = ref([])
const modelTypes = ref([])

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 过滤条件
const filters = reactive({
  model_type: '',
  status: '',
  search: ''
})

// 生命周期钩子
onMounted(async () => {
  await Promise.all([
    fetchActiveModel(),
    fetchModels(),
    fetchModelTypes()
  ])
})

// 获取活动模型
const fetchActiveModel = async () => {
  loadingActiveModel.value = true
  try {
    const res = await getActiveModel()
    activeModel.value = res
  } catch (error) {
    console.error('获取活动模型失败', error)
  } finally {
    loadingActiveModel.value = false
  }
}

// 获取模型列表
const fetchModels = async () => {
  loadingModels.value = true
  try {
    const params = {
      page: pagination.page,
      page_size: pagination.pageSize,
      ...filters
    }
    
    const res = await getModels(params)
    modelsList.value = res.results
    pagination.total = res.count
  } catch (error) {
    console.error('获取模型列表失败', error)
    ElMessage.error('获取模型列表失败')
  } finally {
    loadingModels.value = false
  }
}

// 获取模型类型
const fetchModelTypes = async () => {
  loadingModelTypes.value = true
  try {
    const res = await getModelTypesApi()
    modelTypes.value = res
  } catch (error) {
    console.error('获取模型类型失败', error)
  } finally {
    loadingModelTypes.value = false
  }
}

// 激活模型
const activateModel = async (modelId) => {
  try {
    await activateModelApi(modelId)
    ElMessage.success('模型激活成功')
    
    // 刷新数据
    await Promise.all([
      fetchActiveModel(),
      fetchModels()
    ])
  } catch (error) {
    console.error('激活模型失败', error)
    ElMessage.error('激活模型失败')
  }
}

// 删除模型
const confirmDeleteModel = (model) => {
  ElMessageBox.confirm(
    `确定要删除模型 ${model.name} 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      try {
        await deleteModelApi(model.id)
        ElMessage.success('模型删除成功')
        // 刷新模型列表
        fetchModels()
      } catch (error) {
        console.error('删除模型失败', error)
        ElMessage.error('删除模型失败')
      }
    })
    .catch(() => {})
}

// 查看模型详情
const viewModelDetails = (modelId) => {
  router.push(`/dashboard/models/${modelId}`)
}

// 跳转到模型训练页面
const goToTraining = () => {
  router.push('/model/training')
}

// 跳转到预测页面
const goPrediction = () => {
  router.push('/prediction')
}

// 刷新模型列表
const refreshModels = async () => {
  await Promise.all([
    fetchActiveModel(),
    fetchModels()
  ])
  ElMessage.success('数据已更新')
}

// 处理过滤条件变化
const handleFilterChange = () => {
  pagination.page = 1
  fetchModels()
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchModels()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  pagination.page = val
  fetchModels()
}

// 格式化百分比
const formatPercent = (value) => {
  if (value === null || value === undefined) {
    return '-'
  }
  return `${(value * 100).toFixed(2)}%`
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  switch (status) {
    case 'completed': return 'success'
    case 'training': return 'warning'
    case 'failed': return 'danger'
    default: return 'info'
  }
}
</script>

<style lang="scss" scoped>
.model-overview {
  padding: 20px;
  
  .page-header {
    margin-bottom: 20px;
    
    h1 {
      font-size: 22px;
      font-weight: 500;
      margin: 0;
    }
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .mb-4 {
    margin-bottom: 20px;
  }
  
  .filter-row {
    margin-bottom: 20px;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }
  
  .model-actions {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }
}
</style> 